<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { batchFormRules } from "./utils/rule";
import type { BatchFormItemProps, RechargeApplyAccount, AccountOption, UserOption } from "./utils/types";
import { ElMessage } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";

export interface Props {
  formInline: BatchFormItemProps;
  accountOptions: AccountOption[];
  userOptions: UserOption[];
}

const props = withDefaults(defineProps<Props>(), {
  formInline: () => ({ accounts: [] }),
  accountOptions: () => [],
  userOptions: () => []
});

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);

// 生成唯一key
const generateKey = () => {
  return Date.now().toString() + Math.random().toString(36).substr(2, 9);
};

// 初始化至少一行
if (!newFormInline.value.accounts.length) {
  newFormInline.value.accounts = [
    {
      account_id: "",
      amount: "",
      key: generateKey()
    }
  ];
}

// 添加一行
const addRow = () => {
  newFormInline.value.accounts.push({
    account_id: "",
    amount: "",
    key: generateKey()
  });
};

// 删除一行
const removeRow = (index: number) => {
  if (newFormInline.value.accounts.length <= 1) {
    ElMessage.warning("至少要保留一行申请");
    return;
  }
  newFormInline.value.accounts.splice(index, 1);
  // 重新验证表单
  ruleFormRef.value?.validateField('accounts');
};

// 获取已选择的账号ID列表（用于过滤）
const getSelectedAccountIds = (currentIndex: number) => {
  return newFormInline.value.accounts
    .map((item, index) => index !== currentIndex ? item.account_id : null)
    .filter(id => id);
};

// 监听账号选择变化，触发验证
const handleAccountChange = () => {
  ruleFormRef.value?.validateField('accounts');
};

// 监听金额变化，触发验证
const handleAmountChange = () => {
  ruleFormRef.value?.validateField('accounts');
};

// 处理账号使用者选择
const handleUserChange = (userId: number | string) => {
  if (!userId) {
    // 清空选择，重置为一行
    newFormInline.value.accounts = [
      {
        account_id: "",
        amount: "",
        key: generateKey()
      }
    ];
    return;
  }

  // 查找选中用户的所有账号
  const selectedUser = props.userOptions.find(user => user.value === userId);
  if (selectedUser && selectedUser.accounts && selectedUser.accounts.length > 0) {
    // 为每个账号创建一行申请
    newFormInline.value.accounts = selectedUser.accounts.map(account => ({
      account_id: account.value,
      amount: "",
      key: generateKey()
    }));
  } else {
    // 如果用户没有账号，保持一行空白
    newFormInline.value.accounts = [
      {
        account_id: "",
        amount: "",
        key: generateKey()
      }
    ];
  }

  // 重新验证表单
  ruleFormRef.value?.validateField('accounts');
};

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="batchFormRules"
    label-width="100px"
  >
    <el-form-item label="账号使用者" prop="user_id">
      <el-select
        v-model="newFormInline.user_id"
        placeholder="请选择账号使用者（可选）"
        filterable
        clearable
        style="width: 100%;"
        @change="handleUserChange"
      >
        <el-option
          v-for="option in userOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      <div style="font-size: 12px; color: #999; margin-top: 4px;">
        选择使用者后将自动为该用户的所有广告账号创建充值申请
      </div>
    </el-form-item>

    <el-form-item label="充值申请" prop="accounts">
      <div style="width: 100%;">
        <div
          v-for="(account, index) in newFormInline.accounts"
          :key="account.key"
          style="display: flex; align-items: center; margin-bottom: 12px; gap: 12px; padding: 12px; border: 1px solid #e4e7ed; border-radius: 6px; background: #fafafa;"
        >
          <div style="display: flex; align-items: center; gap: 8px; font-size: 14px; color: #666; min-width: 30px;">
            <el-tag size="small" type="info" style="border-radius: 50%;">{{ index + 1 }}</el-tag>
          </div>

          <el-select
            v-model="account.account_id"
            placeholder="请选择广告账号"
            filterable
            clearable
            style="flex: 1; min-width: 200px;"
            @change="handleAccountChange"
          >
            <el-option
              v-for="option in accountOptions.filter(opt => !getSelectedAccountIds(index).includes(opt.value))"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>

          <el-input
            v-model="account.amount"
            placeholder="充值金额" type="number"
            style="width: 150px;"
            @input="handleAmountChange"
          >
            <template #suffix>
              <span style="color: #999;">$</span>
            </template>
          </el-input>

          <el-button
            v-if="newFormInline.accounts.length > 1"
            type="danger"
            size="small"
            circle
            @click="removeRow(index)"
            :icon="Delete"
          />

          <div v-else style="min-width: 32px;"></div>
        </div>

        <el-button
          type="primary"
          plain
          @click="addRow"
          style="width: 100%; margin-top: 8px;"
        >
          <el-icon style="margin-right: 4px;">
            <Plus />
          </el-icon>
          添加一行
        </el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<style scoped>
:deep(.el-form-item__content) {
  flex-direction: column;
  align-items: stretch;
}

:deep(.el-select) {
  width: 100%;
}
</style>
